/**********************************************************************************
 * 
 * 	功能：	多级菜单处理类
 *  使用说明：
 * 
 * 		1、申明一个实例。传入XML的地址及关键字数组（按菜单级别从大到小排列）
 * 		2、完成后会自动生成一个菜单
 * 
 **********************************************************************************/
 
package org.dstart.object.menulist
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.dstart.object.memo.MemoObject;
	import org.dstart.object.menulist.struct.ClassStruct;
	import org.dstart.object.menulist.sub.MenuIteam;
	
	public class MenuList extends Sprite
	{
		public static const DO_CLICK:String	= "doClick";
			/** 通知外部，执行所选菜单的功能 **/
		
		public static const INIT_DONE:String	= "initDone";
			/** 通知外部，文件读取完毕 **/
		
		public static const LOAD_ERROR:String	= "loadDataError";
			/** 通知外部，读取文件失败 **/
		
		// private var fDebug:FDebug;

		private var myLoad:URLLoader;		/** XML 下载进度条 **/

		private var fileArray:Array;		/** 所有记录列表 **/
		private var totalArray:Array;		/** 分类列表 **/
		private var keywordArray:Array;		/** 关键字列表（按级别顺序排列） **/
		
		private var hotSprite:Sprite;		/** 热响应区块（仅针对部份程序有效）**/
		private var objSprite:Sprite;		/** 对象层 **/
		
		private var objArray:Array;			/** 一级菜单列表 **/
		
		private var nowClickData:Object;	/** 当前所选对象的数据 **/
		
		//	传入参数说明如下
		//		path 	要读取的 XML 文件的路径(目前仅支持 一级目录树)
		//		kArray	一个数组,由 4 个对象组成(至少需要2个对象)
		//			0 号元素,顶级菜单的识别标识
		//			1 号元素,子级菜单的识别标识
		//			2 号元素,项级菜单显示出来的内容标识
		//			3 号元素,子级菜单显示出来的内容标识
		//		以上"标识"都是在  XML 中定义好的变量名,会直接读取其应的值
		//		详细 XML 写法请参见 FileList.xml 或 GameList.xml 中的内容
		//	eg: 
		//		var tArray:Array = new Array("ImgFlashType", "ImgSubType"); 
		//		var tMenu:MenuList = new MenuList("FileList.xml", tArray);
		//		addChild(tMenu);
		//  eg: 
		//		var tMenu:MenuList = new MenuList("GameList.xml", new Array("GameID", "ServerID", "GameName", "ServerName"));
		//		this.addChild(tMenu);
		public function MenuList(path:String, kArray:Array)
		{
			// fDebug = new FDebug();			
			// this.addChild(fDebug);
			
			hotSprite = new Sprite();
			objSprite = new Sprite();
			
			this.addChild(hotSprite);
			this.addChild(objSprite);
			
			fileArray = new Array();
			totalArray = new Array();
			objArray = new Array();
			
			keywordArray = kArray;
			
			if(keywordArray.length < 2)
			{
				throw new Error("错误，传入的关键字数组至少要有两个元素！！");
			}
			
			// trace("input::" + path, kArray);
			
			myLoad = new  URLLoader();
			myLoad.addEventListener(Event.COMPLETE, onLoadDone);			
			myLoad.load(new URLRequest(path));
		}
		
		/** 取得当前所选对象的数据值 **/
		public function get clickData():Object
		{
			return nowClickData;
		}
		
		/** 设置当前所选对象的相关参数 **/
		public function set clickData(obj:Object):void
		{
			nowClickData = obj;
		}
		
		/** 取得菜单项的宽度 **/
		public function get menuWidth():Number
		{
			return this.objSprite.width;
		}
		
		/** 取得菜单项的高度 **/
		public function get menuHeight():Number
		{
			return this.objSprite.height;
		}
		
		/** 绘制一个用于热响应的区块 **/
		public function ShowHotSprite(ww:Number, hh:Number):void
		{
			this.hotSprite.graphics.clear();
			this.hotSprite.graphics.beginFill(0xFFFFFF, 0);
			this.hotSprite.graphics.drawRect(0, 0, ww, hh);
			this.hotSprite.graphics.endFill();
		}
		
		/** 隐藏全部 **/
		public function HiddenAll():void
		{
			for(var i:int = 0; i < objArray.length; i++)
			{
				var tMenu:MenuIteam = objArray[i];
				
				tMenu.model = true;
				tMenu.DeleteSubObject();
				
				RushMenuPlace(tMenu);
			}
			
			this.clickData = null;
			this.dispatchEvent(new Event(DO_CLICK));
		}
		
		/***************************************************************/
		
		private function onLoadDone(e:Event):void
		{
			var m_xml:XML = XML(URLLoader(e.target).data);
			
			fileArray = new Array();
			
			// trace(m_xml.children().length());
			
			for(var i:int = 0; i < m_xml.children().length(); i++)
			{
				var t_xml:XML = m_xml.children()[i];
				var tList:XMLList = t_xml.children();
				var tData:Object = new Object();
				
				// trace(t_xml);

				for(var j:int = 0; j < tList.length(); j++)
				{
					var attName:String = tList[j].name();
					
					tData[attName] = t_xml[attName];
				}

				if(!InsetNewClass(tData))
				{
					// trace("insert Error");
					this.dispatchEvent(new Event(LOAD_ERROR));
					return;
				}
				fileArray.push(tData);
			}
			
			// trace("readDone:" + fileArray);
		
			ShowMenuIteam();
			
			this.dispatchEvent(new Event(INIT_DONE));
		}
		
		/** 插入一条新的列表项 **/
		private function InsetNewClass(mis:Object):Boolean
		{
			try
			{
				//trace(mis);
				
				if(this.keywordArray.length > 0)
				{
					if(mis[keywordArray[0]].toString().length == 0)
					{
						return true;
					}
					else
					{					
						var isFind:Boolean = false;
						var tData:ClassStruct;
						
						for(var i:int = 0; i < totalArray.length; i++)
						{
							var tmpData:ClassStruct = totalArray[i];
							// trace("here1");			
							if(tmpData.CheckIn(mis[keywordArray[0]]))
							{
								tData = tmpData;
								isFind = true;
								break;
							}
						}
						
						if(!isFind)
						{
							// trace("here2");
							tData = new ClassStruct(mis[keywordArray[0]], mis[keywordArray[2]]);
							
							totalArray.push(tData);
						}						
							
						if(this.keywordArray.length > 1)
						{
							if(mis[keywordArray[1]].toString().length == 0)
							{
								return true;
							}
							else
							{
								//if(this.keywordArray.length > 2)
								//{
									/**
									if(mis[keywordArray[2]].toString().length == 0)
									{
										return true;
									}
									else
									{	
										if(!tData.CheckIn(mis[keywordArray[1]], false))
										{
											if(keywordArray.length > 2)
											{
												tData.subArray.push(new ClassStruct(mis[keywordArray[1]], mis[keywordArray[3]]));
											}
											else
											{
												tData.subArray.push(new ClassStruct(mis[keywordArray[1]]));
											}
										}
				
										for(var j:int = 0; j < tData.subArray.length; j++)
										{
											if(tData.subArray[j].CheckIn(mis[keywordArray[1]]))
											{
												if(!tData.subArray[j].CheckIn(mis[keywordArray[2]]))
												{
													if(keywordArray.length > 2)
													{
														tData.subArray[j].subArray.push(new ClassStruct(mis[keywordArray[2]], mis[keywordArray[4]], mis));
													}
													else
													{
														tData.subArray[j].subArray.push(new ClassStruct(mis[keywordArray[2]], "",  mis));
													}
												}
												break;
											}
										}
									} //**/
								//}
								//else
								//{
									if(keywordArray.length > 2)
									{
										tData.subArray.push(new ClassStruct(mis[keywordArray[1]], mis[keywordArray[3]], mis));
									}
									else
									{
										tData.subArray.push(new ClassStruct(mis[keywordArray[1]], "", mis));
									}
									
								//}
							}					
						}
					}
				}
			}
			catch(e:*)
			{
				// trace("处理时发生错误了::" + e);
				return false
			}
			
			return true;
		}
		
		private function ShowMenuIteam():void
		{
			totalArray.sort();
			trace("show");
			
			for(var i:int = 0; i < totalArray.length; i++)
			{
				var tData:ClassStruct = totalArray[i];
				var isShow:Boolean = tData.subArray.length > 0;
				var obj:MenuIteam = CreateNewMenu(this, isShow, tData);
				
				obj.SetPlace(0, i * obj.height);
				
				objArray.push(obj);
				
				objSprite.addChild(obj);
			}
		}
		
		/** 创建一条新的菜单项 **/
		private function CreateNewMenu(spr:Sprite, flag:Boolean, info:ClassStruct):MenuIteam
		{
			var obj:MenuIteam = new MenuIteam(flag);
			obj.text = info.classDisplay;
			obj.info = info;
			if(info.data)
			{
				if(info.data["memo"])
				{
					MemoObject.create(obj, info.data["memo"]);
				}
			}
			obj.addEventListener(MenuIteam.CHANGE_FLAG, onChangeFlagEvent);
			
			trace("create obj::" , obj);
			
			return obj;
		}
		
		/** 菜单被点击后触发 **/
		private function onChangeFlagEvent(e:Event):void
		{
			var tMenu:MenuIteam = MenuIteam(e.target);
			
			tMenu.model = !tMenu.model;
			
			if(!tMenu.model)
			{
				for(var i:int = 0; i < ClassStruct(tMenu.info).subArray.length; i++)
				{
					var tData:ClassStruct = ClassStruct(tMenu.info).subArray[i];
					var isShow:Boolean = Boolean(tData.subArray.length > 0);
					var obj:MenuIteam = CreateNewMenu(tMenu, isShow, tData);
					
					obj.SetPlace(15, (i + 1) * obj.height);
					
					tMenu.addChild(obj);	
				}
			}
			else
			{
				tMenu.DeleteSubObject();
			}
			
			var tSpr:DisplayObject = tMenu;
			
			while(tSpr is MenuIteam)
			{
				RushMenuPlace(tSpr);
				
				tSpr = tSpr.parent;
			}
			
			this.clickData = ClassStruct(tMenu.info).data
			
			//if(this.clickData != null)
			//{
				this.dispatchEvent(new Event(DO_CLICK));
			//}
		}
		
		/** 刷新菜单对象的位置 **/
		private function RushMenuPlace(mIteam:DisplayObject):void
		{
			for(var j:int = 0; j < mIteam.parent.numChildren; j++)
			{
				if(j > mIteam.parent.getChildIndex(mIteam))
				{
					var fSpr:DisplayObject = mIteam.parent.getChildAt(j-1);
					var spr:DisplayObject = mIteam.parent.getChildAt(j);
					
					spr.y = fSpr.y + fSpr.height;
				}
			}
		}
	}
}
